import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { AtForm, AtInput, AtButton, AtMessage, AtRadio } from 'taro-ui'
import { debtorService } from '../../utils/cloud'

export default function DebtorInfo() {
  const [formData, setFormData] = useState({
    name: '',
    cardNumber: '',
    category: 'bank', // 默认选择银行
    remark: ''
  })
  const [loading, setLoading] = useState(false)
  const [isEdit, setIsEdit] = useState(false)

  // 分类选项
  const categoryOptions = [
    { label: '银行', value: 'bank' },
    { label: '小贷', value: 'loan' },
    { label: '亲友', value: 'friend' },
    { label: '信用卡', value: 'credit' }
  ]

  useEffect(() => {
    // 获取路由参数
    const params = Taro.getCurrentInstance().router?.params
    if (params?.id) {
      // 编辑模式，获取数据
      fetchDebtorData(params.id)
      setIsEdit(true)
    }
  }, [])

  // 获取债务人数据
  const fetchDebtorData = async id => {
    try {
      setLoading(true)
      const result = await debtorService.getDebtor(id)

      if (result.success) {
        const debtor = result.data
        setFormData({
          name: debtor.name,
          cardNumber: debtor.cardNumber,
          category: debtor.category || 'bank',
          remark: debtor.remark || ''
        })
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      console.error('获取债务人数据失败:', error)
      Taro.atMessage({
        message: '获取债务人数据失败',
        type: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  const handleInputChange = (value, field) => {
    setFormData({
      ...formData,
      [field]: value
    })
  }

  const handleSave = async () => {
    if (!formData.name || !formData.cardNumber) {
      Taro.atMessage({
        message: '请填写必填项',
        type: 'warning'
      })
      return
    }

    try {
      setLoading(true)
      const params = Taro.getCurrentInstance().router?.params

      let result
      if (isEdit && params?.id) {
        // 更新现有债务人
        result = await debtorService.updateDebtor(params.id, formData)
      } else {
        // 添加新债务人
        result = await debtorService.addDebtor(formData)
      }

      if (result.success) {
        Taro.atMessage({
          message: '保存成功',
          type: 'success'
        })

        // 返回上一页
        setTimeout(() => {
          Taro.navigateTo({ url: '/pages/debtor/index' })
        }, 1500)
      } else {
        throw new Error(result.error)
      }
    } catch (error) {
      console.error('保存失败:', error)
      Taro.atMessage({
        message: '保存失败',
        type: 'error'
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className="min-h-screen bg-gray-100 p-4">
      <AtMessage />

      <View className="bg-white rounded-lg shadow-sm">
        <AtForm>
          <View className="border-b border-gray-100">
            <AtInput
              name="name"
              title="债务人名称"
              type="text"
              value={formData.name}
              onChange={value => handleInputChange(value, 'name')}
              placeholder="请输入债务人名称"
              className="mb-0"
              disabled={loading}
            />
          </View>
          <View className="border-b border-gray-100">
            <AtInput
              name="cardNumber"
              title="债务人卡号"
              type="text"
              value={formData.cardNumber}
              onChange={value => handleInputChange(value, 'cardNumber')}
              placeholder="请输入债务人卡号"
              className="mb-0"
              disabled={loading}
            />
          </View>
          <View className="border-b border-gray-100 p-4">
            <View className="text-gray-700 mb-2">分类</View>
            <AtRadio
              options={categoryOptions}
              value={formData.category}
              onClick={value => handleInputChange(value, 'category')}
              disabled={loading}
            />
          </View>
          <View className="">
            <AtInput
              name="remark"
              title="备注"
              type="text"
              value={formData.remark}
              onChange={value => handleInputChange(value, 'remark')}
              placeholder="请输入备注信息"
              className="mb-0"
              disabled={loading}
            />
          </View>
        </AtForm>
      </View>
      <View className="mt-8">
        <AtButton
          type="primary"
          onClick={handleSave}
          loading={loading}
          disabled={loading}
          className="bg-blue-500 hover:bg-blue-600 text-white shadow-md"
        >
          {loading ? '保存中...' : '保存'}
        </AtButton>
      </View>
    </View>
  )
}
